package com.lib.common.helper.arouter

import android.app.Application
import android.net.Uri
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.launcher.ARouter
//import com.lib.common.constant.INTENT_KEY_ROUTE
import com.lib.common.constant.RouterPathConstant
import com.lib.common.helper.arouter.mapping.PathInfo
import com.lib.common.helper.arouter.mapping.PathMappingFactory
import com.lib.framework.manager.thread.bgThreadRun
import com.lib.framework.utils.AppUtil
import com.lib.framework.utils.StringUtil

/**
 * Copyright (C), 2019-2020
 * FileName: ARouterHelper
 * Author: Kevin
 * Date: 2020-02-19 19:14
 * Description: arouter 辅助类
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
class ARouterHelper {

    companion object {

        /**
         * 初始化
         */
        fun init(application: Application) {
            if (!AppUtil.isReleaseOfVersionType()) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
                ARouter.openLog()     // 打印日志
                ARouter.openDebug()   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
            }

            ARouter.init(application)

            bgThreadRun {
                PathMappingFactory.getInstance()
            }
        }

        /**
         * 跳转到指定页面
         */
        fun navigate(url: String?) {
            navigate(UrlWrapper(url))
        }

        /**
         * 跳转到指定页面
         */
        fun navigate(uri: Uri?) {
            navigate(UrlWrapper(uri))
        }

        /**
         * 跳转到指定页面
         */
        fun navigate(urlWrapper: UrlWrapper) {
            if (!urlWrapper.isValid) {
                return
            }

            val code = urlWrapper.uri.getQueryParameter("code")
            val pathInfo = PathMappingFactory.getInstance().getPathInfoByCode(code) ?: return
            val path = pathInfo.path
            if (path.isNullOrEmpty()) return

            if (path.contains("flutter")) {
                navigateToFlutter(pathInfo, urlWrapper.path)
                return
            }

            try {
                val postcard: Postcard = buildPostcard(path)
                withExtraParameter(postcard, pathInfo.extras)
                withUrlParameter(postcard, urlWrapper.uri)
                postcard.navigation()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        /**
         * 封装 Postcard
         */
        fun buildPostcard(path: String?): Postcard {
            return buildPostcard(ARouter.getInstance().build(path))
        }

        /**
         * 封装 Postcard
         */
        private fun buildPostcard(postcard: Postcard): Postcard {
            val path = postcard.path
            val pathCode = PathMappingFactory.getInstance().getPathCode(path)
            return buildPostcard(postcard, pathCode, path)
        }

        /**
         * 封装 Postcard
         */
        private fun buildPostcard(postcard: Postcard, code: String?, path: String?): Postcard {
            postcard.withString("path", path)
            postcard.withString("xws_path_code", code)
            return postcard
        }

        /**
         * 跳转到 flutter 页面
         */
        private fun navigateToFlutter(pathInfo: PathInfo, urlPath: String) {
//            ARouter.getInstance()
//                .build(RouterPathConstant.PATH_FLUTTER)
//                .withString(INTENT_KEY_ROUTE, urlPath)
//                .navigation()
        }

        /**
         * 写入扩展参数
         */
        private fun withExtraParameter(postcard: Postcard, extras: Map<String, Any>?) {
            if (extras == null) {
                return
            }
            for (key in extras.keys) {
                withParameter(postcard, key, extras[key])
            }
        }

        /**
         * 写入 url 参数
         */
        private fun withUrlParameter(postcard: Postcard, uri: Uri?) {
            if (uri == null) {
                return
            }
            val keys = uri.queryParameterNames
            var value: String?
            for (key in keys) {
                value = uri.getQueryParameter(key)
                withParameter(postcard, key, value)
            }
        }

        /**
         * 写入参数
         */
        private fun withParameter(postcard: Postcard, key: String?, value: Any?): Postcard? {
            var value = value
            if (value is Double) {
                val tmp = value
                if (StringUtil.isIntegerForDouble(tmp)) {
                    value = tmp.toInt()
                }
            }
            if (value is String) {
                var valueString = value as String?
//                if (StringUtil.isInteger(valueString)) {
//                    postcard.withInt(key, Integer.valueOf(valueString!!))
//                } else if (StringUtil.isDouble(valueString)) {
//                    postcard.withDouble(key, java.lang.Double.valueOf(valueString!!))
//                } else if (StringUtil.isLong(valueString)) {
//                    postcard.withDouble(key, java.lang.Long.valueOf(valueString!!).toDouble())
//                } else
                if (StringUtil.isBoolean(valueString)) {
                    postcard.withBoolean(key, java.lang.Boolean.valueOf(valueString))
                } else {
//                    valueString = ParameterUtils.replacePlaceHolderParameter(valueString)
                    postcard.withString(key, valueString)
                }
            } else if (value is Int) {
                postcard.withInt(key, (value as Int?)!!)
            } else if (value is Boolean) {
                postcard.withBoolean(key, (value as Boolean?)!!)
            } else if (value is Double) {
                postcard.withDouble(key, (value as Double?)!!)
            } else if (value is Long) {
                postcard.withLong(key, (value as Long?)!!)
            } else {
                /**
                 * unsupport
                 */
            }
            return postcard
        }
    }
}